<template>
  <div style="padding: 20px;">
    <h1 style="text-align: center;">Combat Script Search</h1>
    <el-row :gutter="20" type="flex" align="middle">
      <el-col :span="3">
        <el-select v-model="searchType" placeholder="请选择搜索类型" style="width: 100%;">
          <el-option label="包含" :value="SEARCH_TYPES.CONTRAIN"></el-option>
          <el-option label="(顺序)包含" :value="SEARCH_TYPES.SEQ_CONTRAIN"></el-option>
          <el-option label="按照脚本id" :value="SEARCH_TYPES.MATCH_ID"></el-option>
        </el-select>
      </el-col>
      <el-col :span="3">
        <el-select v-model="selectedScriptType" placeholder="脚本类型" style="width: 100%;" clearable>
          <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="16">
        <el-input v-model="searchQuery" :placeholder="searchTips" @keyup.enter="handleSearch">
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="handleSearch" style="width: 100%;" :loading="isSearching"
          :disabled="isSearching">
          搜索
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="20" type="flex" align="middle">
      <el-col :span="3">
        <el-button type="primary" @click="showAddDialog" style="width: 100%;">
          新建脚本
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="warning" @click="queryPlaceholder" style="width: 100%;" :loading="isSearching">
          占位查询
        </el-button>
      </el-col>
      <el-col :span="3">
        <el-button type="success" @click="showPlaceholderDialog" style="width: 100%;" :loading="isSubmitting">
          脚本占位
        </el-button>
      </el-col>
      <el-col :span="12">
        <div v-if="totalHits !== null" style="margin-top: 10px;">
              搜索结果： {{ lastQueryIndex }} / {{ lastQueryResult.length }}
        </div>
      </el-col>
    </el-row>

    <div>
      <vxe-table
        ref="tableRef"
        :data="filteredResults"
        :scroll-y="{enabled: true, gt: 50}"
        :row-config="{
          keyField: rowKeyGen,
          isHover: true,
          isCurrent: true
        }"
        :height="tableHeight"
        :loading="isSearching"
        :column-config="{ resizable: true }"
        border
        @cell-click="handleRowClick"
      >
        <vxe-column field="id" title="ID" width="100">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.id?.toString() || ''"
              placement="top"
              :hide-after="0"
              :enterable="true"
              :show-after="500"
            >
              <span>{{ row.id }}</span>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="type_str" title="类型" width="120"></vxe-column>
        <vxe-column field="desc" title="描述" min-width="200">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.desc"
              placement="top"
              :hide-after="0"
              :enterable="true"
              :show-after="500"
              popper-class="desc-tooltip"
            >
              <div class="desc-text" v-html="highlightDesc(row.desc)"></div>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="note" title="备注" width="140">
          <template #default="{ row }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.note"
              placement="top"
              :hide-after="0"
              :enterable="true"
              :show-after="500"
              popper-class="note-tooltip"
            >
              <div class="note-text">{{ row.note }}</div>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button size="small" type="primary" @click.stop="showEditDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click.stop="handleDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <!-- 添加返回顶部按钮 -->
    <el-backtop :right="30" :bottom="30">
      <div class="back-to-top">
        <el-icon>
          <ArrowUpBold />
        </el-icon>
      </div>
    </el-backtop>

    <!-- 添加新脚本的对话框 -->
    <el-dialog v-model="dialogVisible" title="新增脚本" width="50%" :close-on-click-modal="false">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="120px">
        <el-form-item label="脚本ID" prop="id">
          <el-input v-model.number="addForm.id" type="number" />
        </el-form-item>
        <el-form-item label="脚本类型" prop="type_str">
          <el-select v-model="addForm.type_str" placeholder="请选择脚本类型" style="width: 100%;">
            <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="addForm.desc" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="addForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd" :loading="isSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加编辑脚本的对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑脚本" width="50%" :close-on-click-modal="false">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px">
        <el-form-item label="脚本ID">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="脚本类型">
          <el-input v-model="editForm.type_str" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="editForm.desc" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="editForm.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="isSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加脚本占位的对话框 -->
    <el-dialog v-model="placeholderDialogVisible" title="添加脚本占位" width="50%" :close-on-click-modal="false">
      <el-form ref="placeholderFormRef" :model="placeholderForm" :rules="placeholderFormRules" label-width="120px">
        <el-form-item label="脚本类型" prop="type_str">
          <el-select v-model="placeholderForm.type_str" placeholder="请选择脚本类型" style="width: 100%;">
            <el-option v-for="type in scriptTypes" :key="type.value" :label="type.label" :value="type.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="占位个数" prop="count">
          <el-input-number v-model="placeholderForm.count" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="占位文本" prop="text">
          <el-input v-model="placeholderForm.text" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="placeholderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPlaceholder" :loading="isSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, watch, onMounted, onBeforeMount, shallowRef, nextTick, onActivated, onDeactivated, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUpBold } from '@element-plus/icons-vue'

import {
  SEARCH_TYPES,
  type CombatScriptDocument,
  scriptTypeOptions,
  type ESSearchResponse,
  SCRIPT_CONSTANTS,
  SCRIPT_TYPES,
  SCRIPT_TYPES_MAPPING
} from './CombatScriptRepDO'

import {
  buildESQuery,
  esSearchScripts,
  esAddScript,
  esEditScript,
  esDeleteScript,
  esGetMaxId,
  SearchAllCombatScript,
} from './CombatScriptRep'

import type { FormInstance, FormRules } from 'element-plus'

// 全局注册组件
// VxeTableInstance.setup({
//   table: {
//     border: true,
//     stripe: true,
//     showOverflow: true,
//     align: 'center',
//     rowConfig: {
//       isHover: true
//     }
//   }
// })

// ---------------------- vars -----------------------------
// Add cache related variables
const searchCache = ref<{
  key: string;
  results: CombatScriptDocument[];
  totalHits: number;
  timestamp: number;
} | null>(null)

let searchType = ref<number>(SEARCH_TYPES.MATCH_ID)
const searchResults = ref<CombatScriptDocument[]>([])
const scriptTypes = scriptTypeOptions
const searchQuery = ref('')

// Add total hits counter
const totalHits = ref<number | null>(null)
// 分页相关参数
const currentPage = ref(1)
const pageSize = ref(9999)

// Add selected script type ref
const selectedScriptType = ref('')

// 添加新的响应式变量
const tableRef = ref()
const dialogVisible = ref(false)
const isSubmitting = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = ref({
  id: null as number | null,
  type_str: '',
  desc: '',
  note: ''
})

// 表单验证规则
const addFormRules = {
  id: [
    { required: true, message: '请输入脚本ID', trigger: 'blur' },
    { type: 'number', message: 'ID必须为数字', trigger: 'blur' }
  ],
  type_str: [
    { required: true, message: '请选择脚本类型', trigger: 'change' }
  ],
  desc: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ]
} as FormRules

// 添加编辑脚本的响应式变量
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = ref({
  id: null as number | null,
  type_str: '',
  desc: '',
  note: ''
})

// 编辑表单验证规则
const editFormRules = {
  desc: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ]
} as FormRules

// 上次查询条件
let lastQueryContent = ""
let lastQueryScriptType = ""
let lastQueryType = ""

// 查询结果保存
let lastQueryResult: Array<CombatScriptDocument> = []
// 当前查询到的数据位置
let lastQueryIndex = ref(0)

// 添加脚本占位的响应式变量
const placeholderDialogVisible = ref(false)
const placeholderFormRef = ref<FormInstance>()
const placeholderForm = ref({
  type_str: '',
  count: 1,
  text: ''
})

// 占位表单验证规则
const placeholderFormRules = {
  type_str: [
    { required: true, message: '请选择脚本类型', trigger: 'change' }
  ],
  count: [
    { required: true, message: '请输入占位个数', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '个数必须在1到100之间', trigger: 'blur' }
  ],
  text: [
    { required: true, message: '请输入占位文本', trigger: 'blur' }
  ]
} as FormRules

// Add lastSearch state after other ref declarations
const lastSearch = ref<{
  type: number;
  query: string;
} | null>(null)

// 添加虚拟滚动相关配置
const tableHeight = ref(500)

// 添加一个标记变量
const isFirstLoad = ref(true)

// Add resize handler for table height
const updateTableHeight = () => {
  // 计算表格可用高度
  const windowHeight = window.innerHeight
  const tableTop = tableRef.value?.$el?.getBoundingClientRect().top || 0
  const padding = 80 // 底部预留空间
  tableHeight.value = windowHeight - tableTop - padding
}

// Add window resize listener
onMounted(() => {
  console.log("onMounted", Date.now())
  if (isFirstLoad.value) {
    // 只在第一次加载时执行
    window.addEventListener('load', () => {
      console.log("window load")
      clearCache()
    })
    window.addEventListener('resize', updateTableHeight)
    nextTick(() => {
      updateTableHeight()
    })
    reloadCache()
    isFirstLoad.value = false
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', updateTableHeight)
})

// ---------------------- methods -----------------------------

/**
 * 更新上次查询
 */
const updateLastQuery = (queryContent: any, queryType: any, queryScriptType: any, queryResult: Array<CombatScriptDocument>) => {
  lastQueryContent = queryContent
  lastQueryType = queryType
  lastQueryScriptType = queryScriptType
  lastQueryResult = queryResult
  lastQueryIndex.value = 0
}

/**
 * 判断是否是相同的查询条件
 */
const isSameQuery = (queryContent: any, queryType: any, queryScriptType: any) => {
  return lastQueryContent === queryContent && lastQueryType === queryType && lastQueryScriptType === queryScriptType
}

// 优化高亮函数，增加类型检查
const highlightDesc = (desc: string | undefined | null) => {
  if (!desc || typeof desc !== 'string') return ''
  // 使用 replace 而不是正则表达式来提高性能
  return desc.split('列表').join('<span class="highlight-keyword">列表</span>')
}

// 生成el_table每行数据的key
const rowKeyGen = (row: CombatScriptDocument) => {
  const typeKey = SCRIPT_TYPES_MAPPING[row.type_str as keyof typeof SCRIPT_TYPES_MAPPING] || 0
  return typeKey * 100000 + row.id
}

// 修改 performSearch 函数
const isSearching = ref(false)

/**
 * 处理数据：过滤type_str，转换id为整数，并按id排序
 */
const processData = (data: CombatScriptDocument[]): CombatScriptDocument[] => {
  return data
    .filter(item => scriptTypeOptions.some(option => option.value === item.type_str))
    .map(item => ({
      ...item,
      id: typeof item.id === 'string' ? parseInt(item.id, 10) : item.id
    }))
    .sort((a, b) => (a.id || 0) - (b.id || 0))
}

/**
 * 将数据加载到表格 - 优化版本
 */
const loadToTableShow = (data: Array<CombatScriptDocument>) => {
  // 清空现有数据
  searchResults.value = []
  
  // 预处理数据
  const processedData = processData(data)
  
  const chunkSize = 100 // 增加每批次加载的数量
  let index = 0
  
  const loadChunk = () => {
    // 使用性能更好的 slice 直接分割数组
    const chunk = processedData.slice(index, index + chunkSize)
    // 使用 spread operator 一次性添加多条数据
    searchResults.value.push(...chunk)
    
    index += chunkSize
    
    if (index < processedData.length) {
      // 使用 requestAnimationFrame 在下一帧继续加载
      requestAnimationFrame(() => {
        // 如果用户不在查看区域,暂停加载
        if (document.hidden) {
          setTimeout(loadChunk, 100) // 延迟加载
        } else {
          loadChunk()
        }
      })
    } else {
      // 数据加载完成后，如果有类型筛选，显示提示
      if (selectedScriptType.value) {
        const filteredCount = filteredResults.value.length
        const totalCount = searchResults.value.length
        ElMessage.info(`当前显示 ${selectedScriptType.value} 类型的数据：${filteredCount}/${totalCount}`)
      }
    }
  }

  // 使用 requestIdleCallback 在浏览器空闲时开始加载
  if (typeof requestIdleCallback !== 'undefined') {
    requestIdleCallback(() => loadChunk())
  } else {
    requestAnimationFrame(loadChunk)
  }
}

// ============================= cache =====================================
const LOCAL_CACHE_KEY = "ScriptSearchCacheKey"
// Add function to clear cache
const clearCache = () => {
  console.log("clearCache")
  searchCache.value = null
  localStorage.removeItem(LOCAL_CACHE_KEY)
}

/**
 * 更新Cache并存入本地
 */
const updateCache = (data: any) => {
  searchCache.value = {
    key: Date.now().toString(),
    results: data,
    totalHits: data.length,
    timestamp: Date.now()
  }
  localStorage.setItem(LOCAL_CACHE_KEY, JSON.stringify(searchCache.value))
}

/**
 * 加载本地Cache数据转为json数据
 */
const loadLocalCache = async () => {
  const localCache = localStorage.getItem(LOCAL_CACHE_KEY)
  if (localCache == null) {
    const allSearchResult = await SearchAllCombatScript()
    updateCache(allSearchResult)
    console.log("load from remote", Date.now())
    return allSearchResult
  }
  console.log("load from local", Date.now())
  return JSON.parse(localCache).results
}

// 判断是否需要更新Cache
const reloadCache = async () => {
  if (searchCache.value == null && isFirstLoad.value) {
    console.log("reload Cache", Date.now());
    const allSearchResult = await loadLocalCache()
    loadToTableShow(allSearchResult)
    totalHits.value = allSearchResult.length
  }
}

// ======================================= search ====================================

// todo 空查询直接给结果
// Modify performSearch function to use cache
const performSearch = async (resetPage: boolean = true, searchTypeParam?: number, searchQueryParam?: string) => {
  if (isSearching.value) return

  isSearching.value = true
  try {
    if (isSameQuery(searchQuery.value, searchType.value, selectedScriptType.value)) {
      nextMatchSearchResult()
      return
    }

    if (resetPage) {
      currentPage.value = 1
    }

    const currentSearchType = searchTypeParam ?? searchType.value
    const currentSearchQuery = searchQueryParam ?? searchQuery.value

    const query = buildESQuery(
      currentSearchType,
      currentSearchQuery,
      selectedScriptType.value
    )
    console.log("to searching....")
    const response = await esSearchScripts(
      query,
      (currentPage.value - 1) * pageSize.value,
      pageSize.value
    )

    const data = response.data as ESSearchResponse<CombatScriptDocument>
    const queryResult = data.hits.hits.map(hit => ({
      id: typeof hit._source.id === 'string' ? parseInt(hit._source.id, 10) : hit._source.id,
      desc: hit._source.desc,
      note: hit._source.note,
      type_str: hit._source.type_str,
      score: hit._score
    }))
    updateLastQuery(searchQuery.value, searchType.value, selectedScriptType.value, queryResult)
    nextMatchSearchResult()
  } catch (error) {
    console.error('Search failed:', error)
    ElMessage.error('搜索失败，请稍后重试')
    totalHits.value = null
  } finally {
    isSearching.value = false
  }
}

const scrollToRow = (targetRow: any) => {
  tableRef.value.setCurrentRow(targetRow);
  const index = searchResults.value.indexOf(targetRow)
  if (index === -1) return
  
  // Use vxe-table's scrollTo method
  tableRef.value.scrollToRow(targetRow)
}

// 下一条匹配的搜索结果
const nextMatchSearchResult = () => {
  // 重置索引如果超出范围
  if (lastQueryIndex.value >= lastQueryResult.length) {
    lastQueryIndex.value = 0
    ElMessage.info('已回到第一条结果')
  }
  
  const nextSearchResult = lastQueryResult[lastQueryIndex.value]
  if (!nextSearchResult) {
    ElMessage.warning('没有找到匹配结果')
    return
  }
  
  const targetRow = searchResults.value.find(row => rowKeyGen(row) === rowKeyGen(nextSearchResult))
  if (targetRow) {
    scrollToRow(targetRow)
    lastQueryIndex.value++
  } else {
    ElMessage.warning('无法找到对应内容')
  }
}

// 添加计算属性
const searchTips = computed(() => getSearchTips(searchType.value as number))

// 添加排序方法
const sortById = (row: CombatScriptDocument) => {
  const id = typeof row.id === 'string' ? parseInt(row.id, 10) : row.id
  return id || 0
}

// 添加搜索提示文本函数
const getSearchTips = (searchType: number): string => {
  switch (searchType) {
    case SEARCH_TYPES.FUZZY:
      return '请输入要模糊搜索的内容'
    case SEARCH_TYPES.CONTRAIN:
      return '请输入要包含的关键词，多个关键词用空格分隔'
    case SEARCH_TYPES.SEQ_CONTRAIN:
      return '请输入要按顺序包含的关键词，多个关键词用空格分隔'
    case SEARCH_TYPES.MATCH_ID:
      return '请输入脚本ID'
    default:
      return '请先选择搜索类型'
  }
}

// 显示添加对话框
const showAddDialog = () => {
  addForm.value = {
    id: null,
    type_str: '',
    desc: '',
    note: ''
  }
  dialogVisible.value = true
}

// 提交新增表单
const submitAdd = async () => {
  if (!addFormRef.value) return

  await addFormRef.value.validate(async (valid) => {
    if (valid && addForm.value.id !== null) {
      isSubmitting.value = true
      try {
        const response = await esAddScript({
          id: addForm.value.id as number,
          type_str: addForm.value.type_str,
          desc: addForm.value.desc,
          note: addForm.value.note || undefined
        })

        if (response.status === 201) {
          clearCache() // Clear cache after successful add
          // 如果当前页面数据少于页面大小，直接添加列表中
          if (searchResults.value.length < pageSize.value) {
            searchResults.value.push({
              id: addForm.value.id as number,
              type_str: addForm.value.type_str,
              desc: addForm.value.desc,
              note: addForm.value.note,
              score: 0
            })
            // 更新总数
            if (totalHits.value !== null) {
              totalHits.value++
            }
          } else {
            // 如果是满页，则重新加载当前页
            await performSearch(false)
          }

          ElMessage.success('添加成功')
          dialogVisible.value = false
        } else {
          ElMessage.error('添加失败')
        }
      } catch (error: any) {
        console.error('Failed to add script:', error)
        ElMessage.error('添加失败，请稍后重试: ' + error.message)
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 显示编辑对话框
const showEditDialog = (row: CombatScriptDocument) => {
  editForm.value = {
    id: row.id,
    type_str: row.type_str,
    desc: row.desc,
    note: row.note || ''
  }
  editDialogVisible.value = true
}

// 提交编辑表单
const submitEdit = async () => {
  if (!editFormRef.value) return

  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await ElMessageBox.confirm(
          '确定要修改这条记录吗？',
          '确认修改',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )

        isSubmitting.value = true
        const response = await esEditScript({
          id: editForm.value.id!,
          type_str: editForm.value.type_str,
          desc: editForm.value.desc,
          note: editForm.value.note,
          score: 0
        })

        if (response.status === 200) {
          clearCache() // Clear cache after successful edit
          // 更新本地数据，使用id和type_str共同判断
          const index = searchResults.value.findIndex(
            item => item.id === editForm.value.id && item.type_str === editForm.value.type_str
          )
          if (index !== -1) {
            searchResults.value[index] = {
              ...searchResults.value[index],
              desc: editForm.value.desc,
              note: editForm.value.note
            }
          }

          ElMessage.success('修改成功')
          editDialogVisible.value = false
        } else {
          ElMessage.error('修改失败')
        }
      } catch (error: any) {
        if (error !== 'cancel') {
          console.error('Failed to edit script:', error.message)
          ElMessage.error('修改失败，请稍后重试')
        }
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 修改 handleDelete 函数
const handleDelete = async (row: CombatScriptDocument) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？此操作不可恢复！',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    isSubmitting.value = true
    try {
      const response = await esDeleteScript(row.id, row.type_str)

      if (response.status === 200) {
        clearCache() // Clear cache after successful delete
        // 更新本地数据，使用id和type_str共同判断
        searchResults.value = searchResults.value.filter(
          item => !(item.id === row.id && item.type_str === row.type_str)
        )
        // 更新总数
        if (totalHits.value !== null) {
          totalHits.value--
        }

        ElMessage.success('删除成功')
      } else {
        ElMessage.error('删除失败')
      }
    } catch (error) {
      if (error instanceof Error) {
        if (error.message === '文档不存在') {
          ElMessage.warning('该记录已不存在，将从列表中移除')
          // 同样使用id和type_str共同判断
          searchResults.value = searchResults.value.filter(
            item => !(item.id === row.id && item.type_str === row.type_str)
          )
          if (totalHits.value !== null) {
            totalHits.value--
          }
        } else {
          ElMessage.error('删除失败：' + error.message)
        }
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
      console.error('Failed to delete script:', error)
    }
  } catch (error) {
    // 用户取消删除操作
    if (error !== 'cancel') {
      console.error('Delete confirmation failed:', error)
    }
  } finally {
    isSubmitting.value = false
  }
}

// 占位查询函数
const queryPlaceholder = async () => {
  lastSearch.value = {
    type: SEARCH_TYPES.CONTRAIN,
    query: SCRIPT_CONSTANTS.PLACEHOLDER_TEXT
  }
  await performSearch(true, SEARCH_TYPES.CONTRAIN, SCRIPT_CONSTANTS.PLACEHOLDER_TEXT)
}

// 修改搜索按钮点击事件处理
const handleSearch = async () => {
  lastSearch.value = {
    type: searchType.value,
    query: searchQuery.value
  }
  await performSearch(true, searchType.value, searchQuery.value)
}

// 显示占位对话框
const showPlaceholderDialog = () => {
  placeholderForm.value = {
    type_str: '',
    count: 1,
    text: ''
  }
  placeholderDialogVisible.value = true
}

// 提交占位表单
const submitPlaceholder = async () => {
  if (!placeholderFormRef.value) return

  await placeholderFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      try {
        // 获取最大ID
        const maxId = await esGetMaxId(placeholderForm.value.type_str)
        console.log("maxId", maxId)
        const startId = maxId + 1

        // 批量添加脚本
        for (let i = 0; i < placeholderForm.value.count; i++) {
          await esAddScript({
            id: startId + i,
            type_str: placeholderForm.value.type_str,
            desc: `${placeholderForm.value.text}${SCRIPT_CONSTANTS.PLACEHOLDER_TEXT}`,
            note: ""
          })
        }
        clearCache()
        ElMessage.success(`成功添加${placeholderForm.value.count}个占位脚本`)
        placeholderDialogVisible.value = false

        // 执行查询以显示新添加的脚本
        // await performSearch(true, SEARCH_TYPES.CONTRAIN, SCRIPT_CONSTANTS.PLACEHOLDER_TEXT)
      } catch (error: unknown) {
        console.error('Failed to add placeholder scripts:', error)
        if (error instanceof Error) {
          ElMessage.error('添加占位脚本失败：' + error.message)
        } else {
          ElMessage.error('添加占位脚本失败：' + String(error))
        }
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

// 监听 type_str 的变化来更新 count
watch(() => placeholderForm.value.type_str, (newType) => {
  // 根据类型更新 count 的默认值
  placeholderForm.value.count = newType === SCRIPT_TYPES.PASSIVE ? 10 : 1
})

onBeforeMount(() => {
  console.log("beforeMounted", Date.now())
})

// 修改 onMounted 钩子
onMounted(() => {
  console.log("onMounted", Date.now())
  if (isFirstLoad.value) {
    // 只在第一次加载时执行
    window.addEventListener('load', () => {
      console.log("window load")
      clearCache()
    })
    window.addEventListener('resize', updateTableHeight)
    nextTick(() => {
      updateTableHeight()
    })
    reloadCache()
    isFirstLoad.value = false
  }
})

// Add watch for searchQuery
watch(() => searchQuery.value, (newQuery) => {
  // Check if the query is a pure number
  const isNumber = /^\d+$/.test(newQuery.trim())

  // Auto switch search type based on input
  if (isNumber && searchType.value !== SEARCH_TYPES.MATCH_ID) {
    searchType.value = SEARCH_TYPES.MATCH_ID
    console.log('检测到纯数字输入，已自动切换为"按照脚本id"搜索模式')
  } else if (!isNumber && searchType.value === SEARCH_TYPES.MATCH_ID) {
    searchType.value = SEARCH_TYPES.CONTRAIN
    console.log('检测到文本输入，已自动切换为"包含"搜索模式')
  }
})

// 修改 handleRowClick 函数
const handleRowClick = (params: { row: CombatScriptDocument }) => {
  if (!params || !params.row) return
  tableRef.value?.setCurrentRow(params.row)
}

// 修改 activated 钩子
onActivated(() => {
  console.log('Combat script search activated')
  // 不再在这里重新加载数据
})

onDeactivated(() => {
  console.log('Combat script search deactivated')
})

// 在 script setup 部分修改 showTooltipContent 方法
const showTooltipContent = ({ column, row }: any) => {
  if (!row) {
    return column?.title || ''
  }
  const field = column?.field
  if (!field) {
    return ''
  }
  return row[field] || ''
}

// 在 script setup 部分添加计算属性
const filteredResults = computed(() => {
  if (!selectedScriptType.value) {
    return searchResults.value
  }
  return searchResults.value.filter(item => item.type_str === selectedScriptType.value)
})

// 添加对 selectedScriptType 的监听
watch(() => selectedScriptType.value, (newType) => {
  if (newType) {
    const filteredCount = filteredResults.value.length
    const totalCount = searchResults.value.length
    ElMessage.info(`当前显示 ${newType} 类型的数据：${filteredCount}/${totalCount}`)
  }
})
</script>

<style scoped>
/* 移除旧的 el-table 样式 */
/* 添加 vxe-table 相关样式 */
:deep(.vxe-table) {
  border: 1px solid var(--el-border-color);
  background-color: var(--el-bg-color);
}

:deep(.vxe-table--header-wrapper) {
  background-color: var(--el-fill-color-light);
}

:deep(.vxe-table--body-wrapper) {
  background-color: var(--el-bg-color);
}

:deep(.vxe-table--render-default .vxe-body--row.row--current) {
  background-color: var(--el-color-primary-light-5) !important;
  color: var(--el-color-primary-dark-2);
  font-weight: bold;
  box-shadow: 0 0 0 2px var(--el-color-primary) inset;
  transition: all 0.3s ease;
}

:deep(.vxe-table--render-default .vxe-body--row.row--current:hover) {
  background-color: var(--el-color-primary-light-3) !important;
}

:deep(.vxe-table--render-default .vxe-body--row.row--current .vxe-cell) {
  position: relative;
}

:deep(.vxe-table--render-default .vxe-body--row.row--current .vxe-cell::after) {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  border-left: 3px solid var(--el-color-primary);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

:deep(.highlight-keyword) {
  background-color: #ffd04b !important;
  color: #000 !important;
  padding: 2px 4px !important;
  border-radius: 3px !important;
  font-weight: bold !important;
  margin: 0 2px !important;
  border: 1px solid #f0c020 !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

:deep(.desc-tooltip .highlight-keyword) {
  background-color: #ffd04b !important;
  color: #000 !important;
  padding: 2px 4px !important;
  border-radius: 3px !important;
  font-weight: bold !important;
  margin: 0 2px !important;
  border: 1px solid #f0c020 !important;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

/* 保留其他通用样式 */
.el-row {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.back-to-top {
  height: 100%;
  width: 100%;
  background-color: var(--el-bg-color-overlay);
  box-shadow: var(--el-box-shadow-lighter);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: var(--el-transition-all);
}

.back-to-top:hover {
  background-color: var(--el-color-primary-light-9);
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:not(:disabled):hover {
  transform: scale(1.05);
}

.el-button:not(:disabled):active {
  transform: scale(0.95);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.note-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
  cursor: pointer;
}

.desc-text {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}

:deep(.desc-tooltip), :deep(.note-tooltip) {
  max-width: 800px !important;
  white-space: pre-wrap !important;
  word-break: break-all !important;
  font-size: 13px !important;
  padding: 8px 12px !important;
}
</style>
